import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { useRef,useState } from 'react';

import {
  ModalForm,
  ProFormSelect,
  ProFormDatePicker,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Col, Form, message, Popconfirm, Row, Space } from 'antd';
import MyEditor from '@/components/MyEditor';
import { get_dept_list_api } from '@/services/public';
import { get_zubie_list_all_api,delete_api, delete_batch_api, get_list_api, post_save_api,get_files_api } from './api';
import UploadMultiple from '@/components/UploadMultipleLocal';
export default function Page() {
  const ref = useRef<ActionType>();
  const [formAdd] = Form.useForm<MeetingApi.MeetingModelDto>();
  const [formEdit] = Form.useForm<MeetingApi.MeetingModelDto>();
  const [context, setContext] = useState<string>('');
  const [FilesData, setFilesData] = useState<PublicApi.ResAnnexFile[]>([]);
  const columns: ProColumns<NoticeApi.NoticeList>[] = [
    // {
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 48,
    // },
    {
      title: '编号',
      width: 180,
      copyable: true,
      search: false,
      dataIndex: 'id',
      render: (_) => <a>{_}</a>,
    },
    {
      title: '标题',
      width: 160,
      dataIndex: 'title',
    },
    {
      title: '负责人',
      search: false,
      dataIndex: 'head',
    },
    {
      title: '负责人电话',
      search: false,
      dataIndex: 'phone',
    },
    {
      title: '创建人',
      search: false,
      dataIndex: 'createByName',
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '备注',
      search: false,
      dataIndex: 'remarks',
    },
    {
      title: '操作',
      align: 'left',
      width: 140,
      key: 'option',
      valueType: 'option',
      render: (_, row) => {
        return [
          <ModalForm<NoticeApi.NoticeModelDto>
            key="edit"
            title="编辑"
            width={600}
            modalProps={{
              destroyOnClose: true,
              maskClosable: false,
              onCancel: () => {
                setContext(''); 
                setFilesData([]);
              },
            }}
            trigger={
              <a
                onClick={() => {
                  setTimeout(async() => {
                    // 延迟填入数据，为了防止from未创建
                    console.log(row);
                    setContext(row.context);
                    let arrparticipateInDept=row.participateInDept.split(",");
                    row['arrparticipateInDept']=arrparticipateInDept;
                    if(row.groupIn.length>0){
                      row.groupIn=row.groupIn.split(',')
                    }else{
                      row.groupIn=[]
                    }
                    if(row.fileUrl.length>0){
                      const files = await get_files_api(row.fileUrl);
                    
                      const annexs: PublicApi.ResAnnexFile[] = files.data.map((item) => {
                        return {
                          ID: item.id,
                          Name: item.originalName,
                          AnnexType: item.extensionName.substring(1),
                          Path: item.ramark,
                        };
                      });
  
                      setFilesData(annexs)
                    }else{
                      setFilesData([])
                    }
                    

                    formEdit.setFieldsValue(row);
                  }, 100);
                }}
              >
                编辑
              </a>
            }
            form={formEdit}
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              values.id = row.id;
              let str="";
              for(let i=0;i<values['arrparticipateInDept'].length;i++){
                 console.log(i);
                   if(i ===(values['arrparticipateInDept'].length-1)){
                    str=str+values['arrparticipateInDept'][i];
                   }else{
                    str=str+values['arrparticipateInDept']+",";
                   }  
              }
              values.groupIn=values.groupIn.join(',')
              values.context=context;
              values.participateInDept=str;
              values.fileUrl = FilesData.map((item) => {
                return item.ID;
              }).join(',');
              setContext(''); 
              const res = await post_save_api(values);
              console.log(res);
              if (res.success) {
                // 刷新  
                ref.current?.reload();
                message.success('提交成功');
              }

              return res.success;
            }}
          >
          <Row gutter={24}>
            <Col span={12}>
                <ProFormText
                  rules={[{ required: true, message: '请输入标题' }]}
                  placeholder="请输入标题"
                  name="title"
                  label="标题"
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  rules={[{ required: true, message: '请输入负责人' }]}
                  placeholder="请输入负责人"
                  name="head"
                  label="负责人"
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  rules={[{pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,message: '请输入正确的手机号'}]}
                  placeholder="请输入负责人电话"
                  name="phone"
                  label="负责人电话"
                />
              </Col>
              <Col span={24}>
                <ProFormSelect
                  name="groupIn"
                  label="组别"
                  request={async () => {
                    const res = await get_zubie_list_all_api();
                    console.log(res.data);
                    if (res.data.length > 0) {
                      const list = res.data.map((item: any) => {
                        return {
                          label: item.groupName,
                          value: item.id,
                        };
                      });

                      return list;
                    }
                    return [];
                  }}
                  fieldProps={{
                    mode: "multiple",
                  }}
                  placeholder="请选择组别"
                  
                />
              </Col>
              <Col span={24}>
                <ProFormTreeSelect
                  name="arrparticipateInDept"
                  label="部门"
                  request={async () => {
                    const res = await get_dept_list_api();
                    console.log(res.data);
                    if (res.data.length > 0) {
                      return res.data;
                    }
                    return [];
                  }}
                  fieldProps={{
                    showArrow: true,
                    showSearch: true,
                    multiple:true,
                    dropdownMatchSelectWidth: false,
                    autoClearSearchValue: true,
                    filterTreeNode: true,
                    treeNodeFilterProp: 'deptName',
                    fieldNames: { label: 'deptName', value: 'id', children: 'routes' },
                  }}
                  placeholder="请选择部门"
                  
                />
              </Col>
              <Col span={24}>
                <MyEditor
                  onChange={(e) => {
                    setContext(e);
                  }}
                  placeholder="请输入内容"
                  label="内容"
                  value={context}
                ></MyEditor>
              </Col>
              <Col span={24}>
                <UploadMultiple
                  isCamera={false}
                  label="文件"
                  initValue={FilesData}
                  onChange={async (e) => {
                    //新增
                    // console.log(e);

                    setFilesData(e);
                  }}
                  onDelete={async (e) => {
                    // console.log(e);
                    //删除
                    setFilesData(e);
                  }}
                />
              </Col>
              <Col span={24}>
                <ProFormTextArea placeholder="请输入备注" name="remarks" label="备注" />
              </Col>
            </Row>
          </ModalForm>,

          <Popconfirm
            key="delete"
            title="删除"
            description="确认删除此条数据?"
            onConfirm={async () => {
              console.log(row.id);
              const res = await delete_api(row.id);
              if (res.success) {
                // 刷新
                ref.current?.reload();
                message.success('删除成功');
              }
            }}
            onCancel={() => {
              message.error('删除已取消');
            }}
            okText="是"
            cancelText="否"
          >
            <a style={{ color: '#F56C6C' }}>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<NoticeApi.NoticeList>
        actionRef={ref}
        request={async (params = {}) => {
          const columnFilters: any = {};
          Object.keys(params).forEach((key) => {
            if (key !== 'current' && key !== 'pageSize') {
              columnFilters[key] = {
                eq: '%',
                name: key,
                value: params[key],
              };
            }
          });
          const res = await get_list_api({
            columnFilters: columnFilters,
            pageNum: params?.current ?? 1,
            pageSize: params?.pageSize ?? 10,
          });

          return {
            page: params?.current,
            data: res.data.records,
            success: true,
            total: res.data.total,
          };
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        columns={columns}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          onChange: () => {},
        }}
        tableAlertOptionRender={({ selectedRows, onCleanSelected }) => {
          return (
            <Space size={16}>
              <Popconfirm
                key="delete"
                title="批量删除"
                description="确认删除这些数据?"
                onConfirm={async () => {
                  const listKeys = selectedRows.map((item) => item.id);
                  // console.log(listKeys);

                  const res = await delete_batch_api(listKeys);
                  if (res.success) {
                    onCleanSelected();
                    // 刷新
                    ref.current?.reload();
                    message.success('删除成功');
                  }
                }}
                onCancel={() => {
                  message.error('删除已取消');
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{ color: '#F56C6C' }}>批量删除</a>
              </Popconfirm>
              {/* <a>导出数据</a> */}
            </Space>
          );
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <ModalForm<MeetingApi.MeetingModelDto>
            key="add"
            title="新增"
            width={600}
            modalProps={{
              destroyOnClose: true,
              maskClosable: false,
              onCancel: () => {},
            }}
            trigger={
              <Button type="primary" key="primary">
                新增
              </Button>
            }
            form={formAdd}
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (values) => {
              let str="";
              for(let i=0;i<values.participateInDept.length;i++){
                 console.log(i);
                   if(i ===(values.participateInDept.length-1)){
                    str=str+values.participateInDept[i];
                   }else{
                    str=str+values.participateInDept+",";
                   }  
              }
              values.groupIn=values.groupIn.join(',')
              values.context=context;
              values.participateInDept=str;
              values.fileUrl = FilesData.map((item) => {
                return item.ID;
              }).join(',');
              console.log(values);
              setContext('');
              const res = await post_save_api(values);
              console.log(res);
              if (res.success) {
                // 刷新
                ref.current?.reload();
                message.success('提交成功');
              }
              return res.success;
            }}
          >
            <Row gutter={24}>
            <Col span={12}>
                <ProFormText
                  rules={[{ required: true, message: '请输入标题' }]}
                  placeholder="请输入标题"
                  name="title"
                  label="标题"
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  rules={[{ required: true, message: '请输入负责人' }]}
                  placeholder="请输入负责人"
                  name="head"
                  label="负责人"
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  rules={[{pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,message: '请输入正确的手机号'}]}
                  placeholder="请输入负责人电话"
                  name="phone"
                  label="负责人电话"
                />
              </Col>
              <Col span={24}>
                <ProFormSelect
                  name="groupIn"
                  label="组别"
                  request={async () => {
                    const res = await get_zubie_list_all_api();
                    console.log(res.data);
                    if (res.data.length > 0) {
                      const list = res.data.map((item: any) => {
                        return {
                          label: item.groupName,
                          value: item.id,
                        };
                      });

                      return list;
                    }
                    return [];
                  }}
                  fieldProps={{
                    mode: "multiple",
                  }}
                  placeholder="请选择组别"
                  
                />
              </Col>
              <Col span={24}>
                <ProFormTreeSelect
                  name="participateInDept"
                  label="部门"
                  request={async () => {
                    const res = await get_dept_list_api();
                    console.log(res.data);
                    if (res.data.length > 0) {
                      return res.data;
                    }
                    return [];
                  }}
                  fieldProps={{
                    showArrow: true,
                    multiple:true,
                    showSearch: true,
                    dropdownMatchSelectWidth: false,
                    autoClearSearchValue: true,
                    filterTreeNode: true,
                    treeNodeFilterProp: 'deptName',
                    fieldNames: { label: 'deptName', value: 'id', children: 'routes' },
                  }}
                  placeholder="请选择部门"
                  
                />
              </Col>
              <Col span={24}>
                <MyEditor
                  onChange={(e) => {
                    setContext(e);
                  }}
                  placeholder="请输入内容"
                  label="内容"
                  value={context}
                ></MyEditor>
              </Col>
              <Col span={24}>
                <UploadMultiple
                  isCamera={false}
                  label="文件"
                  initValue={FilesData}
                  onChange={async (e) => {
                    //新增
                    // console.log(e);

                    setFilesData(e);
                  }}
                  onDelete={async (e) => {
                    // console.log(e);
                    //删除
                    setFilesData(e);
                  }}
                />
              </Col>
              <Col span={24}>
                <ProFormTextArea  placeholder="请输入备注" name="remarks" label="备注" />
              </Col>
            </Row>
          </ModalForm>,
        ]}
      />
    </PageContainer>
  );
}
